package sein.android.hopenote;

import java.util.ArrayList;

import sein.android.hopenote.Const.HopeNoteDb;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TableLayout;
import android.widget.Toast;

public class HopeNoteMainActivity extends TabActivity {

	private DBAdapter HnopenHelper;
	private SQLiteDatabase sdb;
	static public TabHost tabHost;
	//Intent note_search;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.hopenote_main);
        //app 최초실행시 database 생성
        HnopenHelper = new DBAdapter(this);
        
        sdb = HnopenHelper.getReadableDatabase();
        
        IntentFilter filter = new IntentFilter("BR_Main");
		registerReceiver(BR_Main,filter);
        
        //TabHost tabHost = (TabHost)findViewById(R.id.tabhost);
        tabHost = getTabHost();
        //tabHost.setup();
        
        SharedPreferences cache = getSharedPreferences("cache", Activity.MODE_PRIVATE);
        HopeNoteDb.CURRENT_USER = cache.getString("USER", "");
        setTitle(HopeNoteDb.CURRENT_USER);
        

		if(HopeNoteDb.CURRENT_ITEM.equals(""))
		{
			Cursor c_item = sdb.rawQuery("SELECT " + HopeNoteDb.COL_ITEM + "," + HopeNoteDb.COL_GROUP + "," + HopeNoteDb.COL_UNIT + "," + HopeNoteDb.COL_CNT + " FROM " + HopeNoteDb.TB_ITEM + " limit 1", null);
			if(c_item.getCount() > 0)
			{
				c_item.moveToFirst();
				HopeNoteDb.CURRENT_ITEM = c_item.getString(0);
				HopeNoteDb.CURRENT_GROUP = c_item.getString(1);
				HopeNoteDb.CURRENT_UNIT = c_item.getString(2);
				HopeNoteDb.CURRENT_CNT = c_item.getString(3);
			}
		}

        
        //HopeNoteDb.CURRENT_USER = getString(R.string.user_name);
        
        //LayoutInflater inflater = LayoutInflater.from(this);
        //inflater.inflate(R.layout.hopenote_main, tabHost.getTabContentView(),true);
        
        //TabHost.TabSpec spec = ;        
        //spec.setIndicator("입력");
        tabHost.addTab(tabHost.newTabSpec("tag1").setIndicator("",getResources().getDrawable(R.drawable.btn_input)).setContent(new Intent(this,Note_Input_Tab.class)));
        
        //spec = tabHost.newTabSpec("tag2");
        //spec.setContent(R.id.tab_search);
        //spec.setIndicator("검색");
        //tabHost.addTab(spec.setContent(new Intent(this,Note_Search.class)));
        //tabHost.addTab(tabHost.newTabSpec("tag2").setIndicator("검색").setContent(new Intent(this,Note_Search.class)));
        tabHost.addTab(tabHost.newTabSpec("tag2").setIndicator("",getResources().getDrawable(R.drawable.btn_searchitem)).setContent(new Intent(this,Note_Search_Tab.class)));
        tabHost.addTab(tabHost.newTabSpec("tag3").setIndicator("",getResources().getDrawable(R.drawable.btn_searchtime)).setContent(new Intent(this,Note_Day_Tab.class)));
        tabHost.addTab(tabHost.newTabSpec("tag4").setIndicator("",getResources().getDrawable(R.drawable.btn_chart)).setContent(new Intent(this,Note_Chart_Tab.class)));
        
        
        
      //Tab Widget 설정
        for (int tab = 0; tab < tabHost.getTabWidget().getChildCount(); ++tab) {
        	//tabHost.getTabWidget().getChildAt(tab).getLayoutParams().height *= 0.5;//= HopeNoteDb.TAB_WIDGET_HEIGHT;
        	tabHost.getTabWidget().getChildAt(tab).setBackgroundResource(R.drawable.tab_input);
        }
        
        //tabHost.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_input));
        
        //tabHost.focusableViewAvailable(getTabWidget().setBackgroundColor(Color.parseColor("FFEEEE")));
        //tabHost.getTabWidget().setBackgroundResource(R.drawable.tab_input);
        
        tabHost.setCurrentTab(0);
        
		final InputMethodManager IMM = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        
        tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			
			public void onTabChanged(String tabId) {
				// TODO Auto-generated method stub
				IMM.hideSoftInputFromWindow(tabHost.getWindowToken(), 0);
				tabHost.requestFocus();
			}
		});
    }
    
   

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.activity_main, menu);
		super.onCreateOptionsMenu(menu);
		MenuItem item = null;
		switch(tabHost.getCurrentTab()){
		case 0:
			//item = menu.add(0,1,0,"짜장");
			//item.setIcon(R.drawable.ic_action_search);
			//item.setAlphabeticShortcut('a');
			menu.add(0,1,0,"사용자").setIcon(R.drawable.icon_user);
			menu.add(0,2,0,"항목관리").setIcon(R.drawable.icon_gear);
			return true; 
		case 1:
			menu.add(0,1,0,"사용자").setIcon(R.drawable.icon_user);
			menu.add(0,3,0,"항목").setIcon(R.drawable.icon_item);
			menu.add(0,4,0,"파일로 저장").setIcon(R.drawable.icon_excel);
			return true;
		case 2:
			menu.add(0,1,0,"사용자").setIcon(R.drawable.icon_user);
			menu.add(0,5,0,"파일로 저장").setIcon(R.drawable.icon_excel);
			return true;
		case 3:
			menu.add(0,1,0,"사용자").setIcon(R.drawable.icon_user);
			menu.add(0,3,0,"항목").setIcon(R.drawable.icon_item);
			return true;
		}
		return false;		
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		//getTabHost();
		TabHost.TabSpec spec = null;
		switch(item.getItemId()){
		case 1:
			Intent list = new Intent(this, User_List.class);
			startActivity(list);
			return true;
		case 2:
			HopeNoteDb.IS_NEW_GROUP = true;
			Intent item_input = new Intent(this, Item_Input.class);
			startActivity(item_input);			
			return true;
		case 3:
			
			/*
			final Intent note_search = new Intent(this, Note_Search.class);
			//get category from DB
			Cursor grp_cur = sdb.query(HopeNoteDb.TB_ITEM, new String[] {HopeNoteDb.COL_GROUP}, null, null, HopeNoteDb.COL_GROUP, null, null);
			grp_cur.moveToFirst();
	        final CharSequence[] grp_list = new CharSequence[grp_cur.getCount()];
	        for(int i = 0; i < grp_cur.getCount(); i++){
	        	grp_list[i] = grp_cur.getString(0);
	        	grp_cur.moveToNext();
	        }
	        grp_cur.close();
	        
	        //set Dialog
			AlertDialog.Builder chooseCtg = new AlertDialog.Builder(HopeNoteMainActivity.this);
			chooseCtg.setTitle("항목 선택");
			chooseCtg.setItems(grp_list, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					note_search.putExtra("category",grp_list[which].toString());
					View v = Note_Search_Tab.SearchTabGroup.getLocalActivityManager().startActivity("Group_Sel", note_search.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
					Note_Search_Tab.SearchTabGroup.replaceView(v);
				}
			});
			chooseCtg.show();
			*/
			
			Intent item_set = new Intent(this, Item_Set.class);
			//startActivityForResult(item_set, HopeNoteDb.REQ_ITEM_SET);
			startActivity(item_set);
			return true;
			
		case 4:
			
			AlertDialog.Builder dialog_fileout_item = new AlertDialog.Builder(this);
			dialog_fileout_item.setMessage("기록을 저장할 방법을 선택하세요.").setCancelable(false).setPositiveButton("e-Mail", 
					new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent note_fileout = new Intent("Emailout_item");
							sendBroadcast(note_fileout);
						}
					}).setNegativeButton("file", 
					new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent note_fileout = new Intent("Fileout_item");
							sendBroadcast(note_fileout);
						}
					});
			
			AlertDialog alert_item = dialog_fileout_item.create();
			alert_item.setTitle("기록 저장");
			alert_item.setIcon(R.drawable.hopenote);
			alert_item.show();
			
			return true;
			
		case 5:
			
			AlertDialog.Builder dialog_fileout_day = new AlertDialog.Builder(this);
			dialog_fileout_day.setMessage("기록을 저장할 방법을 선택하세요.").setCancelable(false).setPositiveButton("e-Mail", 
					new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent note_day_fileout = new Intent("Emailout_day");
							sendBroadcast(note_day_fileout);
						}
					}).setNegativeButton("file", 
					new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Intent note_day_fileout = new Intent("Fileout_day");
							sendBroadcast(note_day_fileout);
						}
					});
			
			AlertDialog alert_day = dialog_fileout_day.create();
			alert_day.setTitle("기록 저장");
			alert_day.setIcon(R.drawable.hopenote);
			alert_day.show();
			
			return true;
			
		}
		return false;
	}
	
	private BroadcastReceiver BR_Main = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			setTitle(HopeNoteDb.CURRENT_USER);
		}
	};
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(BR_Main);
	};
}
